<?php

namespace common\models\datas;

use common\components\bases\BaseModel;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use common\components\helpers\Fun;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\components\extenders\MenuManage;

/**
 * This is the model class for table "{{%card_send}}".
 *
 * @property integer $id
 * @property integer $number
 * @property integer $user_id
 * @property integer $salesman_id
 * @property integer $batch_id
 * @property integer $card_start
 * @property integer $card_end
 * @property integer $created_at
 * @property integer $proportion
 * @property integer $parent_id
 * @property integer $site_id
 * @property integer $commission_rate
 * @property integer $is_withdraw
 */
class CardSend extends BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%card_send}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['number', 'user_id', 'salesman_id', 'issuser_id', 'batch_id', 'card_start', 'card_end', 'created_at', 'dues_proportion', 'site_id', 'send_type', 'commission_rate', 'proportion'], 'integer'],
            [['dues_desc'], 'string'],
            [['batch_id', 'salesman_id', 'card_start', 'card_end', 'commission_rate'], 'required', 'except' => 'sendcard'],
            [['card_start', 'card_end'], 'check_number'],
            [['salesman_id', 'number', 'proportion'], 'required', 'on' => 'sendcard'],
            [['number'], 'check_numbers', 'on' => 'sendcard'],
            [['salesman_id'], 'check_salesman_id', 'on' => 'sendcard'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', 'ID'),
            'number' => Yii::t('common', '发卡数量'),
            'user_id' => Yii::t('common', '创建用户'),
            'salesman_id' => Yii::t('common', '发卡人'),
            'batch_id' => Yii::t('common', '所属批次'),
            'card_start' => Yii::t('common', '开始编号'),
            'card_end' => Yii::t('common', '结束编号'),
            'created_at' => Yii::t('common', '创建时间'),
            'dues_proportion' => Yii::t('common', '优惠会费比例'),
            'dues_desc' => Yii::t('common', '优惠比例说明'),
            'site_id' => Yii::t('common', '分店id'),
            'issuser_id' => Yii::t('common', '推荐人id'),
            'send_type' => Yii::t('common', '发卡类型（0实体卡 1推荐卡）'),
            'commission_rate' => Yii::t('common', '佣金比例'),
            'proportion' => Yii::t('common', '分成比例'),
            'parent_id' => Yii::t('common', '父级id'),
            'is_withdraw' => Yii::t('common', '是否为被回收卡'),
        ];
    }


    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
            ],

        ]);
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        return $fields;
    }

    public function extraFields()
    {
        return [
            'salesman_name' => function () {
                $str = isset($this->isuserinfo) ? (!empty($this->isuserinfo->name) ? $this->isuserinfo->name . '-' : '') : '';
                $str .= isset($this->isuserinfo) ? (!empty($this->isuserinfo->contact) ? $this->isuserinfo->contact . '-' : '') : '';
                $str .= isset($this->isuserinfo) ? $this->isuserinfo->mobile : '';
                if (empty($str)) {
                    $str = isset($this->customer) ? $this->customer->name : '';
                }
                return $str;
            },
            'admin_name' => function () {
                return ($this->admin != null) ? $this->admin->username : '';
            },
            'count' => function () {
                return $this->cardattrcount;
            },
            'activationcount' => function () {
                return $this->cardattractivationcount;
            },
            'batch_name' => function () {
                return isset($this->cardBatch) ? $this->cardBatch->title : '';
            },
            'isuser_name' => function () {
                $response_id = isset($this->isuserinfo->response_man) ? $this->isuserinfo->response_man : '';
                if ($response_id != null) {
                    $response = Admin::findOne(['id' => $response_id]);
                }
                $response_name = isset($response->name) ? $response->name : '';
                return $response_name;
            },
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'cardresent' => function () {
                            if ($this->cardattractivationcount == 0) {
                                return '<button class="yx-btn-disabled" type="button">使用详情</button>';
                            } else {
                                return '';
                            }
                        }
                    ]
                )->create();
            },
            'operate1' => function () {
                if ($this->cardattractivationcount == 0) {
                    return "<a href='#' rel='action-handle' data-action='cardclass'>未使用</a>";
                } else {
                    return "<a href='/orderstatistic-cardresend?id={$this->id}' rel='action-handle' data-action='cardclass'>使用详情</a>";
                }
            },
            'zhtfrontend_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
            },
        ];
    }

    public function check_number($attribute)
    {
        if ($this->card_start != null && $this->card_end != null) {
            $card_id = CardAttr::find()->select('card_id')->where(['batch_id' => $this->batch_id])->orderBy('card_id asc')->column();
            $min_card_id = $card_id[0];
            $max_card_id = end($card_id);
            if ($this->card_start < $min_card_id) {
                $this->addError($attribute, Yii::t('frontend', '开始编号必须大于该批次的开始编号{min_card_id}!', ['min_card_id' => $min_card_id]));
            }
            if ($this->card_end > $max_card_id) {
                $this->addError($attribute, Yii::t('frontend', '结束编号必须小于该批次的结束编号{max_card_id}!', ['max_card_id' => $max_card_id]));
            }
            if ($this->card_end < $this->card_start) {
                $this->addError($attribute, Yii::t('frontend', '结束编号不能小于开始编号!'));
            }
            if ($this->batch_id > 0) {
                $count = CardAttr::find()->where(['status' => 0, 'batch_id' => $this->batch_id])->count();
                if ($this->card_end - $this->card_start + 1 > $count) {
                    $this->addError($attribute, Yii::t('frontend', '最多发卡数量为{count}', ['count' => $count]));
                }
            }
            $count = CardAttr::find()->where(['between', 'card_id', $this->card_start, $this->card_end])->andWhere('status>0')->count();
            if ($count > 0) {
                $this->addError($attribute, Yii::t('frontend', '起止号码区间不连续!'));
            }
        }
    }

    public function check_numbers($attribute)
    {
        if (!empty($this->parent_id)) {
            $card_send = CardSend::findOne(['id' => $this->parent_id]);
            if ($card_send === null) {
                $this->addError('card_send_id', Yii::t('wechatzht', '发卡信息不存在'));
            } else {
                $card_re_send = CardSend::find()->where(['batch_id' => $card_send->batch_id, 'site_id' => $card_send->site_id, 'parent_id' => $this->parent_id])->andWhere(['!=', 'parent_id', 0])->all();
                $count = 0;
                foreach ($card_re_send as $k => $v) {
                    $count += $v->number;
                }
                $surplus = $card_send->number - $count;
                if ($this->$attribute > $surplus) {
                    $this->addError($attribute, Yii::t('wechatzht', '最多发卡数量为{count}', ['count' => $surplus]));
                }
            }
        }
    }

    public function check_salesman_id($attribute)
    {
        if ($this->$attribute == 0) {
            $this->addError($attribute, Yii::t('wechatzht', '请选择二次发卡人'));
        }

    }

    public function getAdmin()
    {
        return $this->hasOne(Admin::className(), ['id' => 'user_id']);
    }


    public function getCardBatch()
    {
        return $this->hasOne(CardBatch::className(), ['id' => 'batch_id']);
    }

    public function getIsuserinfo()
    {
        return $this->hasOne(IsuserInfo::className(), ['id' => 'salesman_id']);
    }

    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['id' => 'salesman_id']);
    }

    public function getCardattrcount()
    {
        return $this->hasMany(CardAttr::className(), ['salesman_id' => 'salesman_id'])->count();
    }

    public function getCardattractivationcount()
    {
        return $this->hasMany(CardAttr::className(), ['salesman_id' => 'salesman_id'])->where(['status' => 1, 'batch_id' => $this->batch_id])->andWhere(['>', 'customer_id', 0])->count();
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            $count = CardAttr::find()->where(['status' => 0, 'batch_id' => $this->batch_id])->count();
            if ($count == 0) {
                $command = \Yii::$app->db->createCommand('UPDATE {{%card_batch}} SET status=3 WHERE id=:id');
                $command->bindValue(':id', $this->batch_id);
                $command->execute();
            }
        }
    }
}

